package cn.tianyigps.tianyigpsgatherchecker.service;

import cn.tianyigps.tianyigpsgatherchecker.bean.EquipmentCheckModel;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

@Service
public class FindLicensePlate {
    @Autowired
    FindCarAllEquIds findCarAllEquIds;
    private final  static  String SUCCESS = "200";
    public HashSet findLicensePlate(List<EquipmentCheckModel> equipmentCheckModelList ) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        HashSet<String> set = new HashSet<>();
        HashSet<String> existedSet = new HashSet<>();
        HashSet<String> resultSet = new HashSet<>();
        for(EquipmentCheckModel equipmentCheckModel : equipmentCheckModelList){
            set.add(equipmentCheckModel.getEquipmentId());
        }
        if (set.isEmpty()){
            return null;
        }

        Iterator<String> setIterator = set.iterator();
        while (setIterator.hasNext()) {

            String equipmentId = setIterator.next();
            if(existedSet.contains(equipmentId)){
                continue;
            }
            String rest = findCarAllEquIds.findCarAllEquIds(equipmentId);

            JsonNode jsonObject = mapper.readTree(rest);
            String status = jsonObject.get("status").toString();
            if (SUCCESS.equals(status)) {
                Iterator<JsonNode> elements = jsonObject.elements();
                while(elements.hasNext()) {
                    JsonNode node = elements.next();
                    //set中放入车辆信息
                    existedSet.add(node.get("code").toString());
                    //存入最后一个同车设备的车牌或车架号，然后将已查出的设备号放入已查找结果中
                    if (!elements.hasNext()) {
                        //没有车牌号，放入车架号
                        String str = node.get("license_plate").toString();
                        String vinCode = node.get("vin_code").toString();
                        if (!StringUtils.isEmpty(str)) {
                            resultSet.add(str);
                        } else {
                            if (!StringUtils.isEmpty(vinCode)) {
                                resultSet.add(vinCode);
                            }
                        }
                    }
                }
            }else {
                setIterator.remove();
            }
        }
        return  resultSet;
    }
}
